package com.abel.bigwater.dataserver.model.ewide

import io.netty.buffer.ByteBuf
import org.slf4j.LoggerFactory

class TermUploadReqData(_pduLen: Int = -1) : TermData(KmingDataType.TermUploadReq, _pduLen) {
    var frameCount: Int? = null

    var channelList: ArrayList<KmingChannelType> = ArrayList()

    override fun bufLength() = 1 + 2 + channelList.size

    override fun parseBuf(buf: ByteBuf): Boolean {
        if (pduLen < 3) {
            throw IllegalArgumentException("dataLen should be initialized before parsing")
        }

        buf.apply {
            assert(type == KmingDataType.findByCode(readUnsignedByte()))

            frameCount = readUnsignedShortLE()

            val channelCount = pduLen - 1 - 2
            for (i in 0 until channelCount) {
                val kc = readUnsignedByte()
                val kt = KmingChannelType.findByCode(kc)
                if (kt != null) {
                    channelList.add(kt)
                } else {
                    channelList.add(KmingChannelType.DummyChannel)
                    lgr.error("unknown channel type: ${kc.toString(16)}H")
                }
            }
        }

        return true
    }

    override fun pack(buf: ByteBuf) {
        buf.alloc().buffer().apply {
            writeByte(type.code.toInt())

            writeShortLE(frameCount!!)

            for (ch in channelList) {
                writeByte(ch.code.toInt())
            }

            buf.writeBytes(this)
        }
    }

    override fun toString(): String {
        return "{type:$type,frame-count:${frameCount},channel:${channelList.joinToString()}}"
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(TermUploadReqData::class.java)
    }
}